package com.ruoyi.web.controller.basedata;

import java.util.List;
import java.util.Objects;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.basedata.domain.TerminalsDb;
import com.ruoyi.basedata.domain.TerminalsXb;
import com.ruoyi.basedata.service.ITerminalsDbService;
import com.ruoyi.basedata.service.ITerminalsXbService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basedata.domain.UsageRange;
import com.ruoyi.basedata.service.IUsageRangeService;

import static com.ruoyi.basedata.domain.UsageRange.COMMON_FLAG;

/**
 * 用量区间设置Controller
 *
 * @author TsingYu
 * @date 2024-07-13
 */
@RestController
@RequestMapping("/basedata/usageRange")
public class UsageRangeController extends BaseController {
    private final IUsageRangeService usageRangeService;
    private final ITerminalsXbService terminalsXbService;
    private final ITerminalsDbService terminalsDbService;

    public UsageRangeController(IUsageRangeService usageRangeService, ITerminalsXbService terminalsXbService, ITerminalsDbService terminalsDbService) {
        this.usageRangeService = usageRangeService;
        this.terminalsXbService = terminalsXbService;
        this.terminalsDbService = terminalsDbService;
    }

    /**
     * 获取用量区间设置详细信息
     */
    @PreAuthorize("@ss.hasPermi('basedata:usage_range:query')")
    @GetMapping(value = "/{tenantId}/{warnTargetType}")
    public AjaxResult getInfo(@PathVariable("tenantId") String tenantId, @PathVariable("warnTargetType") String warnTargetType) {
        List<UsageRange> usageRanges = usageRangeService.selectUsageRangeByTenantId(tenantId, warnTargetType);
        if (!COMMON_FLAG.equals(tenantId)) {
            List<UsageRange> commonUsageRanges = usageRangeService.selectUsageRangeByTenantId(COMMON_FLAG, warnTargetType);
            usageRanges.addAll(0, commonUsageRanges);
        }
        return success(usageRanges);
    }

    /**
     * 新增用量区间设置
     */
    @Log(title = "用量区间设置", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('basedata:usage_range:add')")
    @PostMapping
    public AjaxResult add(@RequestBody @Validated UsageRange usageRange) {
        try {
            SysUser user = getLoginUser().getUser();
            if (!Objects.equals(user.getSystemFlag(), Constants.SYS_FLAG_ADMIN) && COMMON_FLAG.equals(usageRange.getTenantId())) {
                return error("无权限新增或修改通配值！");
            }
            if (COMMON_FLAG.equals(usageRange.getTenantId())) {
                usageRange.setStrategy(COMMON_FLAG);
            } else if (StringUtils.isBlank(usageRange.getStrategy())) {
                usageRange.setStrategy(IdUtil.fastSimpleUUID().toUpperCase());
            }
            LambdaQueryWrapper<UsageRange> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(UsageRange::getStrategyName, usageRange.getStrategyName())
                    .ne(UsageRange::getStrategy, usageRange.getStrategy())
                    .eq(UsageRange::getWarnTargetType, usageRange.getWarnTargetType())
                    .eq(UsageRange::getTenantId, usageRange.getTenantId());
            long nameCount = usageRangeService.count(wrapper);
            if (nameCount > 0) {
                return error(String.format("策略：%s已存在，请更换名称！", usageRange.getStrategyName()));
            }
            return toAjax(usageRangeService.insertUsageRange(usageRange));
        } catch (Exception e) {
            return error(e.toString());
        }
    }

    /**
     * 删除指定用量区间设置
     *
     * @return AjaxResult
     */
    @PreAuthorize("@ss.hasPermi('basedata:usage_range:remove')")
    @Log(title = "删除指定用量区间设置", businessType = BusinessType.DELETE)
    @DeleteMapping
    public AjaxResult removeByPrimaryKey(@RequestBody String requestBody) {
        try {
            String tenantId = JsonUtils.getString(requestBody, "tenantId");
            String warnTargetType = JsonUtils.getString(requestBody, "warnTargetType");
            String strategy = JsonUtils.getString(requestBody, "strategy");
            Boolean forceDelete = JsonUtils.getBoolean(requestBody, "forceDelete");
            // 强制删除标志，会清空已经与之关联的终端的策略
            boolean force = forceDelete != null && forceDelete;
            if (StringUtils.isAnyBlank(tenantId, warnTargetType, strategy)) {
                return error("客户id、报警对象类型、策略均不能为空！");
            }
            if (COMMON_FLAG.equals(tenantId) && COMMON_FLAG.equals(strategy)) {
                return error("无法删除通配值");
            }
            String label = DictUtils.getDictLabel("warn_target_type", warnTargetType);
            if (UsageRange.WARN_TARGET_TYPE_DB.equals(warnTargetType)) {
                // 大表
                if (force) {
                    LambdaUpdateWrapper<TerminalsDb> updateWrapper = Wrappers.lambdaUpdate();
                    updateWrapper.eq(TerminalsDb::getStrategy, strategy)
                            .set(TerminalsDb::getStrategy, "");
                    terminalsDbService.update(updateWrapper);
                } else {
                    LambdaQueryWrapper<TerminalsDb> queryWrapper = Wrappers.lambdaQuery();
                    queryWrapper.eq(TerminalsDb::getStrategy, strategy)
                            .eq(TerminalsDb::getDelFlag, 0);
                    long count = terminalsDbService.count(queryWrapper);
                    if (count > 0) {
                        return error(String.format("无法删除已使用的%s策略！", label));
                    }
                }
            } else if (UsageRange.WARN_TARGET_TYPE_XB.equals(warnTargetType)) {
                // 小表
                if (force) {
                    LambdaUpdateWrapper<TerminalsXb> updateWrapper = Wrappers.lambdaUpdate();
                    updateWrapper.eq(TerminalsXb::getStrategy, strategy)
                            .set(TerminalsXb::getStrategy, "");
                    terminalsXbService.update(updateWrapper);
                } else {
                    LambdaQueryWrapper<TerminalsXb> queryWrapper = Wrappers.lambdaQuery();
                    queryWrapper.eq(TerminalsXb::getStrategy, strategy)
                            .eq(TerminalsXb::getDelFlag, 0);
                    long count = terminalsXbService.count(queryWrapper);
                    if (count > 0) {
                        return error(String.format("无法删除已使用的%s策略！", label));
                    }
                }
            }
            LambdaUpdateWrapper<UsageRange> deleteWrapper = Wrappers.lambdaUpdate();
            deleteWrapper.eq(UsageRange::getTenantId, tenantId)
                    .eq(UsageRange::getWarnTargetType, warnTargetType)
                    .eq(UsageRange::getStrategy, strategy);
            return toAjax(usageRangeService.remove(deleteWrapper));
        } catch (Exception e) {
            logger.error("删除指定用量区间设置", e);
            return error("操作失败");
        }

    }
}
